package com.lhy.utilsdemo.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author Liu Hangyu
 * @date 2021/12/13 10:52
 */
@Component
public class WebSocketServer {
    @Autowired
    private WebSocketHandler webSocketHandler;

    @Value("${websocket.port}")
    private int port;


    @PostConstruct
    public void ServerBootstrap() {

        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                //测试远程客户端是否没响应了
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //设置TCP属性
                //Nagle算法试图减少TCP包的数量和结构性开销, 将多个较小的包组合成较大的包进行发送.但这不是重点, 关键是这个算法受TCP延迟确认影响, 会导致相继两次向连接发送请求包,
                //读数据时会有一个最多达500毫秒的延时.
                .childOption(ChannelOption.TCP_NODELAY, true)
                //等待队列
//               .childOption(ChannelOption.SO_BACKLOG,1024)
                //允许重复监听端口 快速服用
                .childOption(ChannelOption.SO_REUSEADDR, true)
                //开始进行逻辑
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //mqtt编码器
                        nioSocketChannel.pipeline().addLast(new HttpServerCodec());
                        //mqtt解码
                        nioSocketChannel.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
                        //添加WebSocket编解码
                        nioSocketChannel.pipeline().addLast(new WebSocketServerProtocolHandler("/mqttws"));
                        //心跳
//                        nioSocketChannel.pipeline().addLast(new ReadTimeoutHandler(5, TimeUnit.SECONDS));
                        //注入自己的处理器 webSocket处理器
                        nioSocketChannel.pipeline().addLast(webSocketHandler);

                    }
                });
        try {
            //设置生成端口 用的是配置文件的
            serverBootstrap.bind(port).sync();
            System.out.println("webSocket启动");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
